package com.alibaba.cirtus.ots.application.app.ability.facade.v2serviceimpl;

import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcorder.model.dto.EmployeeGetCurrentLoginResponse;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdRequest;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneByIdResponse;
import com.epoch.app.bcorder.model.dto.QueryCargoZoneListWithAccessRequest;
import com.epoch.app.bcorder.model.dto.WarehouseInfo;
import com.epoch.app.bcorder.service.BcOrderService;
import com.epoch.app.bcorder.service.UnifiedInventoryService;
import com.epoch.app.crb2btradecenter.otsb2btradecenter.service.OtsB2bTradeCenterService;
import com.epoch.app.crforecastsales.api.forecastorderlinequery.service.ForecastOrderLineQueryService;
import com.epoch.app.crforecastsales.api.forecastorderwrite.service.ForecastOrderWriteService;
import com.epoch.app.crforecastsales.dto.request.SubmitForecastRequest;
import com.epoch.app.crforecastsales.enums.ForecastStatusEnum;
import com.epoch.app.crforecastsales.model.dto.ApiContext;
import com.epoch.app.crforecastsales.model.dto.CreateForecastOrderParamsRequest;
import com.epoch.app.crforecastsales.model.dto.CreateForecastOrderParamsResponse;
import com.epoch.app.crforecastsales.model.dto.QueryGoodsDetailListRequest;
import com.epoch.app.crforecastsales.sdo.ForecastOrderLineSDO;
import com.epoch.app.crforecastsales.sdo.ForecastOrderSDO;
import com.epoch.app.crforecastsales.sdo.ScItemGoods;
import com.epoch.app.crforecastsales.service.CrForecastSalesService;
import com.epoch.app.crplatformenhance.api.customeraddressquery.service.CustomerAddressQueryService;
import com.epoch.app.crplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.crplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.crplatformenhance.goodsfavorites.model.GoodsFavorites;
import com.epoch.app.crplatformenhance.goodsfavorites.service.GoodsFavoritesService;
import com.epoch.app.crplatformenhance.model.dto.GetLoginEmployOrganizationPermissionsPriceRequest;
import com.epoch.app.crplatformenhance.model.dto.GoodsFavoritesItem;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAddressListByPrincipalRequest;
import com.epoch.app.crplatformenhance.model.dto.PageQueryAddressListByPrincipalResponse;
import com.epoch.app.crplatformenhance.model.dto.QueryAddressDetailResponse;
import com.epoch.app.crplatformenhance.model.dto.QueryEnumValuesRequest;
import com.epoch.app.crplatformenhance.sdo.CustomerAddressSDO;
import com.epoch.app.crplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.crplatformenhance.service.CrPlatformEnhanceService;
import com.epoch.app.crpricecenter.api.creditquery.service.CreditQueryService;
import com.epoch.app.crpricecenter.model.dto.CreditInfoSDO;
import com.epoch.app.crpricecenter.model.dto.CreditQueryRequest;
import com.epoch.app.crunifiedinventory.api.allocaterelationread.dto.QueryAllocateRelationForOrderRequest;
import com.epoch.app.crunifiedinventory.api.allocaterelationread.service.AllocateRelationReadService;
import com.epoch.app.crunifiedinventory.sdo.AllocateRelationSDO;
import com.epoch.app.crunifiedinventory.service.CrUnifiedInventoryService;
import com.epoch.app.otsapplicationappsdk.createplanreportalorder.dto.AsyncSubmitRequest;
import com.epoch.app.otsapplicationappsdk.createplanreportalorder.dto.RenderRequest;
import com.epoch.app.otsapplicationappsdk.createplanreportalorder.dto.SubmitRequest;
import com.epoch.app.otsapplicationappsdk.createplanreportalorder.service.CreatePlanReportalOrderService;
import com.google.gson.internal.LinkedTreeMap;
import lombok.Data;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
import java.util.stream.Collectors;


@Service
public class CreatePlanReportalOrderV2ServiceImpl implements CreatePlanReportalOrderService {
    public static final String SHANGHAI_ORG_CODE = "6255";
    private static Log log = Log.getLogger(CreatePlanReportalOrderV2ServiceImpl.class);
    private static final String DATE_FORMAT_STR_STAN = "yyyy-MM-dd HH:mm:ss";
    private static final List<Info> FILTER_ORDER_TYPE = new ArrayList<Info>() {{
        add(new Info() {{
            setLabel("标准预报订单");
            setValue("01");
        }});
        /*add(new Info() {{
            setLabel("车销预报订单");
            setValue("02");
        }});*/

    }};

    @Autowired
    private ForecastOrderLineQueryService forecastOrderLineQueryService;

    @Autowired
    private CrForecastSalesService otsForecastSalesService;


    @Autowired
    private ForecastOrderWriteService forecastOrderWriteService;

    @Autowired
    private OtsB2bTradeCenterService otsB2bTradeCenterService;

    @Autowired
    private CrPlatformEnhanceService otsPlatformEnhanceService;

    @Autowired
    private CrUnifiedInventoryService otsUnifiedInventoryService;

    @Autowired
    private UnifiedInventoryService unifiedInventoryService;

    @Autowired
    private CustomerAddressQueryService customerAddressQueryService;

    @Autowired
    private AllocateRelationReadService allocateRelationReadService;

    @Autowired
    private CreditQueryService creditQueryService;

    @Autowired
    private OrganizationQueryService organizationQueryService;

    @Autowired
    private GoodsFavoritesService favoritesService;

    @Autowired
    private BcOrderService bcOtsService;

    @Resource(name = "forecastSaleTaskExecutor")
    private ThreadPoolTaskExecutor forecastSaleTaskExecutor;

    @Override
    public Object render(RenderRequest renderRequest) {
        CreateSelectList createSelectList = new CreateSelectList();
        createSelectList.setDisableRefNo(Boolean.FALSE);
        QueryGoodsDetailListRequest queryGoodsListRequest = new QueryGoodsDetailListRequest();

        EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
        if (Objects.nonNull(employeeGetCurrentLoginResponse)){
            String organizationType = employeeGetCurrentLoginResponse.getRelatedOrganizationType();
            //103为分子公司 不做条件设置
            switch (organizationType){
                case "104":
                    queryGoodsListRequest.setOrganizationCode(employeeGetCurrentLoginResponse.getRelatedOrganizationId());
                    break;
                case "105":
                    //查询组织的code
                    String organizationCode = getTopLevelCode(employeeGetCurrentLoginResponse.getRelatedOrganizationId(), 104);
                    if (Objects.nonNull(organizationCode)){
                        queryGoodsListRequest.setOrganizationCode(organizationCode);
                    }
                    queryGoodsListRequest.setSaleChannelCode(organizationCode);
                    break;
                case "106":
                    //查询组织的code
                    String departOrganizationCode = getTopLevelCode(employeeGetCurrentLoginResponse.getRelatedOrganizationId(), 104);
                    queryGoodsListRequest.setOrganizationCode(departOrganizationCode);

                    //查询渠道的code
                    String departChannelCode = getTopLevelCode(employeeGetCurrentLoginResponse.getRelatedOrganizationId(), 105);
                    queryGoodsListRequest.setSaleChannelCode(departChannelCode);


                    queryGoodsListRequest.setDepartmentCode(employeeGetCurrentLoginResponse.getRelatedOrganizationId());
                    break;
                default:
                    queryGoodsListRequest.setOrganizationCode("");
                    break;
            }

            if (employeeGetCurrentLoginResponse.getIsSales()){
                queryGoodsListRequest.setSalesmanCode(employeeGetCurrentLoginResponse.getEmployeeId());
            }
            if (Integer.parseInt(organizationType)>=104){
                //是否禁用采购订单号
                Result<List<OrganizationSDO>> loginEmployOrganizationPermissionsPrice = otsPlatformEnhanceService.getLoginEmployOrganizationPermissionsPrice(new GetLoginEmployOrganizationPermissionsPriceRequest() {{
                    setType(104);
                }});
                if (Objects.nonNull(loginEmployOrganizationPermissionsPrice)&&CollectionUtils.isNotEmpty(loginEmployOrganizationPermissionsPrice.getResult())){
                    OrganizationSDO organizationSDO = loginEmployOrganizationPermissionsPrice.getResult().get(0);
                    if (SHANGHAI_ORG_CODE.equalsIgnoreCase(organizationSDO.getCode())){
                        createSelectList.setDisableRefNo(Boolean.TRUE);
                    }
                }

            }
        }
        //前端透传常用货品code，下发到接口返回常用货品类目


        Result<List<GoodsFavorites>> goodsFavoritesResult = favoritesService.queryGoodsFavoritesForForecastSale();
        log.info("查询货品收藏夹出参:"+JSONObject.toJSONString(goodsFavoritesResult));
        if (Objects.nonNull(goodsFavoritesResult)&&CollectionUtils.isNotEmpty(goodsFavoritesResult.getResult())){
            GoodsFavorites goodsFavorites = goodsFavoritesResult.getResult().get(0);
            String goodsList = goodsFavorites.getGoodsList();
            if (StringUtils.isNotBlank(goodsList)&&!"[]".equalsIgnoreCase(goodsList)){
                List<GoodsFavoritesItem> goodsFavoritesItems = JSONObject.parseArray(goodsList, GoodsFavoritesItem.class);
                List<String> goodsCodes = goodsFavoritesItems.stream().map(GoodsFavoritesItem::getGoodsCode).collect(Collectors.toList());
                queryGoodsListRequest.setGoodsFavoritesList(goodsCodes);
            }
        }

        queryGoodsListRequest.setRecentlyUsedItemIdList(renderRequest.getGoodsIdList());
//        Callable<List<ScItemGoods>> scItemCallable = () -> forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();
//        Future<List<ScItemGoods>> task = new FutureTask<>(scItemCallable);
//        new Thread((Runnable) task).start();


//        CompletableFuture<List<ScItemGoods>>  future = CompletableFuture.supplyAsync(() -> {
//            List<ScItemGoods> scItemGoodsList = forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();
//            if (scItemGoodsList != null && CollectionUtils.isNotEmpty(scItemGoodsList)) {
//                return scItemGoodsList;
//            }
//            return null;
//            }, forecastSaleTaskExecutor);

        List<ScItemGoods> scItemGoodsList = forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();



        //配送方式
        List<Info> deliveryType = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("shipMethod");
        }}))).getString("result"), List.class);
        QueryCargoZoneListWithAccessRequest queryCargoZoneListWithAccessRequest = new QueryCargoZoneListWithAccessRequest();
        queryCargoZoneListWithAccessRequest.setTypeList(Arrays.asList(3,4));
        List<WarehouseInfo> sendList = bcOtsService.queryCargoZoneListWithAccess(queryCargoZoneListWithAccessRequest).getResult();
        if (CollectionUtils.isNotEmpty(sendList)) {
            List<Info> deliveryHouse = sendList.stream().map(x -> {
                Info info = new Info();
                info.setLabel(x.getName());
                info.setValue(x.getId());
                return info;
            }).collect(Collectors.toList());
            createSelectList.setDeliveryWarehouse(deliveryHouse);
        }




        createSelectList.setOrderType(FILTER_ORDER_TYPE);
        createSelectList.setDeliveryType(deliveryType);

        createSelectList.setScItemGoodsList(scItemGoodsList);
        createSelectList.setGoodsIdList(renderRequest.getGoodsIdList());
//        try {
////            createSelectList.setScItemGoodsList(task.get());
////            createSelectList.setScItemGoodsList(future.get());
//        } catch (InterruptedException | ExecutionException e) {
//            log.error("小程序创建销售预报单获取货品异常:"+e.getMessage());
//            e.printStackTrace();
//        }
        return createSelectList;
    }

    /**
     * asyncSubmit
     */
    @Override
    public Object asyncSubmit(AsyncSubmitRequest asyncSubmitRequest) {
        long l1 = System.currentTimeMillis();
        JSONObject requestInput = (JSONObject) JSONObject.toJSON(asyncSubmitRequest.getRequestInput());

        JSONArray goodsIdJson = requestInput.getJSONObject("fields").getJSONObject("updateFields").getJSONArray("goodsIdList");
        List goodsIdList = null;
        if (goodsIdJson != null) {
            goodsIdList = JSONObject.parseArray(goodsIdJson.toJSONString(),Object.class);
        }

        //前端透传常用货品code，下发到接口返回常用货品类目
        QueryGoodsDetailListRequest queryGoodsListRequest = new QueryGoodsDetailListRequest();

        //从客户地址上取组织信息 如果没有异常，应取此货品集合
        Future<List<ScItemGoods>> taskAddressScItem = null;
        CompletableFuture<List<ScItemGoods>>  future = null;
        List<ScItemGoods> scItemGoodsList = null;

        String addressCode = requestInput.getJSONObject("fields").getJSONObject("updateFields").getString("addressValue");
        String addressId = requestInput.getJSONObject("fields").getJSONObject("updateFields").getString("addressId");
        //JSONObject bizModel = requestInput.getJSONObject("fields").getJSONObject("bizModel");
        JSONObject bizModel = new JSONObject();

        //页面模块上的其他模块的选中value
        JSONObject tempSaveValue = requestInput.getJSONObject("fields").getJSONObject("tempSaveValue");
        tempSaveValue.put("addressCode",addressCode);

        bizModel.put("tempSaveValue", tempSaveValue);
        //收货地址 选中一条收货地址 查询出对应的客户信息和组织信息
      /*  List list = otsPlatformEnhanceService.pageQueryAddressList(new PageQueryAddressListRequest() {{
            setAddressCode(addressCode);
        }}).getResult();*/

        PageQueryAddressListByPrincipalResponse listResult = otsPlatformEnhanceService.pageQueryAddressListByPrincipal(new PageQueryAddressListByPrincipalRequest() {{
            setId(addressId);
        }});

        if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())) {
            JSONObject relationInfo = (JSONObject) JSONObject.toJSON(listResult.getResult().get(0));

            QueryAddressDetailResponse queryAddressDetailResponse = null;

            String itemGroup = relationInfo.getString("itemGroup");
            String channelCode = relationInfo.getString("channelCode");
            String customerCode = relationInfo.getString("customerCode");
            String organizationCode = relationInfo.getString("orgSaleOrganizationCode");
            String orgSaleDepartmentCode = relationInfo.getString("orgSaleDepartmentCode");
            String orgSaleChannelCode = relationInfo.getString("orgSaleChannelCode");
            String salesmanCode = relationInfo.getString("principal");


            try {

                //查询用户信用额度
                if (Objects.nonNull(relationInfo)) {
                    CreditQueryRequest queryCreditRequest = new CreditQueryRequest();
                    queryCreditRequest.setChannelCode(channelCode);
                    queryCreditRequest.setCustomerCode(customerCode);
                    queryCreditRequest.setOrganizationCode(organizationCode);
                    queryCreditRequest.setItemGroupCode(itemGroup);
                    Result<CreditInfoSDO> creditReponseResult = creditQueryService.queryCreditBalance(queryCreditRequest);
                    if (creditReponseResult.isSuccess() && Objects.nonNull(creditReponseResult.getResult())) {
                        relationInfo.put("creditBalance", creditReponseResult.getResult().getBalance());
                        relationInfo.put("feeBalance", creditReponseResult.getResult().getFeeBalance());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            bizModel.put("chooseAddress", relationInfo);

            if (StringUtils.isBlank(tempSaveValue.getString("addressCode"))) {
                tempSaveValue.put("addressCode", addressCode);
            }
            if (StringUtils.isBlank(tempSaveValue.getString("addressId"))) {
                tempSaveValue.put("addressId", addressId);
            }

            try {
                QueryAllocateRelationForOrderRequest queryAllocateRelationForOrderRequest = new QueryAllocateRelationForOrderRequest();
                queryAllocateRelationForOrderRequest.setAddressCode(relationInfo.getString("addressCode"));
                queryAllocateRelationForOrderRequest.setOrganizationCode(relationInfo.getString("orgSaleOrganizationCode"));
                queryAllocateRelationForOrderRequest.setSaleChannelCode(relationInfo.getString("orgSaleChannelCode"));
                queryAllocateRelationForOrderRequest.setSaleDepartmentCode(relationInfo.getString("orgSaleDepartmentCode"));
                //查询客户的关联关系，用户查询出货品仓，客户姓名等关系
//                Result<List<AllocateRelationSDO>> pageQueryAllocateRelationResponse = allocateRelationReadService.pageQueryAllocateRelation(queryAllocateRelationRequest);
                Result<List<AllocateRelationSDO>> pageQueryAllocateRelationResponse = allocateRelationReadService.queryAllocateRelationForOrder(queryAllocateRelationForOrderRequest);
                if (Objects.nonNull(pageQueryAllocateRelationResponse) && CollectionUtils.isNotEmpty(pageQueryAllocateRelationResponse.getResult())) {
                    bizModel.put("wareHouseInfo", pageQueryAllocateRelationResponse.getResult().get(0));
                    if (StringUtils.isBlank(tempSaveValue.getString("wareHouseCode"))) {
                        tempSaveValue.put("wareHouseCode", pageQueryAllocateRelationResponse.getResult().get(0).getWareHouseCode());
                    }
                }
                try {
                    queryGoodsListRequest.setChannelCode(channelCode);
                    queryGoodsListRequest.setSalesmanCode(salesmanCode);
                    queryGoodsListRequest.setSaleChannelCode(orgSaleChannelCode);
                    queryGoodsListRequest.setOrganizationCode(organizationCode);
                    queryGoodsListRequest.setDepartmentCode(orgSaleDepartmentCode);
                    queryGoodsListRequest.setRecentlyUsedItemIdList(goodsIdList);
                    if (Objects.nonNull(tempSaveValue.get("wareHouseCode"))&&StringUtils.isNotBlank(String.valueOf(tempSaveValue.get("wareHouseCode")))){
                        queryGoodsListRequest.setWarehouseCode(String.valueOf(tempSaveValue.get("wareHouseCode")));
                    }


                    Result<List<GoodsFavorites>> goodsFavoritesResult = favoritesService.queryGoodsFavoritesForForecastSale();
                    log.info("查询货品收藏夹出参:"+JSONObject.toJSONString(goodsFavoritesResult));
                    if (Objects.nonNull(goodsFavoritesResult)&&CollectionUtils.isNotEmpty(goodsFavoritesResult.getResult())){
                        GoodsFavorites goodsFavorites = goodsFavoritesResult.getResult().get(0);
                        String goodsList = goodsFavorites.getGoodsList();
                        if (StringUtils.isNotBlank(goodsList)&&!"[]".equalsIgnoreCase(goodsList)){
                            List<GoodsFavoritesItem> goodsFavoritesItems = JSONObject.parseArray(goodsList, GoodsFavoritesItem.class);
                            List<String> goodsCodes = goodsFavoritesItems.stream().map(GoodsFavoritesItem::getGoodsCode).collect(Collectors.toList());
                            queryGoodsListRequest.setGoodsFavoritesList(goodsCodes);
                        }
                    }

//                    Callable<List<ScItemGoods>> scItemCallableWithAddress = () -> forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();
//                    taskAddressScItem = new FutureTask<>(scItemCallableWithAddress);
//                    new Thread((Runnable) taskAddressScItem).start();


//                        future = CompletableFuture.supplyAsync(() -> {
//                        List<ScItemGoods> scItemGoodsList = forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();
//                        if (scItemGoodsList != null && CollectionUtils.isNotEmpty(scItemGoodsList)) {
//                            return scItemGoodsList;
//                        }
//                        return null;
//                    }, forecastSaleTaskExecutor);
                    scItemGoodsList = forecastOrderLineQueryService.queryGoodsDetailList(queryGoodsListRequest).getResult().getScItemGoodsList();


                }catch (Exception e){
                    log.error("根据地址附带组织信息查询货品列表:",e);
                }

            } catch (Exception e) {
                e.printStackTrace();
                log.error("获取关联发货仓数据失败：" + e.getMessage());
            }

        }else {
            return Result.fail("","查询收货地址异常");
        }

        bizModel.put("tempSaveValue", tempSaveValue);
        log.info("tempSaveValue:" + tempSaveValue.toJSONString());
        //单据类型
       /* List<Info> orderType = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("forecastTag");
        }}))).getString("result"), List.class);

        List<Info> filterOrderType = Nullable.stream(orderType).filter(o -> !FILTER_ORDER_TYPE.contains(o.getValue())).collect(Collectors.toList());

*/
       // List<Info> filterOrderType=new ArrayList<Info>(){{add(new Info(){{setLabel("标准预报订单");setValue("01");}});add(new Info(){{setLabel("车销预报订单");setValue("02");}});}};

        ///配送方式
        List<Info> deliveryType = JSONObject.parseObject(JSONObject.parseObject(JSONObject.toJSONString(otsPlatformEnhanceService.queryEnumValues(new QueryEnumValuesRequest() {{
            setCode("shipMethod");
        }}))).getString("result"), List.class);

        QueryCargoZoneListWithAccessRequest queryCargoZoneListWithAccessRequest = new QueryCargoZoneListWithAccessRequest();
        queryCargoZoneListWithAccessRequest.setTypeList(Arrays.asList(3,4));
        List<WarehouseInfo> sendList = bcOtsService.queryCargoZoneListWithAccess(queryCargoZoneListWithAccessRequest).getResult();
        if (CollectionUtils.isNotEmpty(sendList)) {
            List<Info> deliveryHouse = sendList.stream().map(x -> {
                Info info = new Info();
                info.setLabel(x.getName());
                info.setValue(x.getId());
                return info;
            }).collect(Collectors.toList());
            bizModel.put("deliveryWarehouse", deliveryHouse);
        }
        bizModel.put("disableRefNo",Boolean.FALSE);
        EmployeeGetCurrentLoginResponse employeeGetCurrentLoginResponse = bcOtsService.employeeGetCurrentLogin();
        if (Objects.nonNull(employeeGetCurrentLoginResponse)){
            String organizationType = employeeGetCurrentLoginResponse.getRelatedOrganizationType();
            if (Integer.parseInt(organizationType)>=104){
                //是否禁用采购订单号
                Result<List<OrganizationSDO>> loginEmployOrganizationPermissionsPrice = otsPlatformEnhanceService.getLoginEmployOrganizationPermissionsPrice(new GetLoginEmployOrganizationPermissionsPriceRequest() {{
                    setType(104);
                }});
                if (Objects.nonNull(loginEmployOrganizationPermissionsPrice)&&CollectionUtils.isNotEmpty(loginEmployOrganizationPermissionsPrice.getResult())){
                    OrganizationSDO organizationSDO = loginEmployOrganizationPermissionsPrice.getResult().get(0);
                    if (SHANGHAI_ORG_CODE.equalsIgnoreCase(organizationSDO.getCode())){
                        bizModel.put("disableRefNo",Boolean.TRUE);
                    }
                }

            }
        }

        bizModel.put("orderType", FILTER_ORDER_TYPE);
        bizModel.put("deliveryType", deliveryType);
        bizModel.put("scItemGoodsList", scItemGoodsList);
//        try {
////         bizModel.put("scItemGoodsList", taskAddressScItem.get());
//
//        } catch (InterruptedException | ExecutionException e) {
//            log.error("小程序创建销售预报单异步获取货品异常:"+e.getMessage());
//            e.printStackTrace();
//        }
        return bizModel;
    }

    @Override
    public Object submit(SubmitRequest submitRequest) {

        // log.info("submitRequest:" + JSONObject.toJSONString(submitRequest));
        JSONObject requestInput = (JSONObject) JSONObject.toJSON(submitRequest.getRequestInput());
        JSONObject result = new JSONObject();

        String submitType = requestInput.getJSONObject("fields").getJSONObject("submitFields").getJSONObject("bottomButton").getString("submitType");
        JSONObject submitFields = requestInput.getJSONObject("fields").getJSONObject("submitFields");

        if (Objects.nonNull(submitFields)) {
            CreateForecastOrderParamsResponse forecastOrderParams = planOrderSubmit(submitFields, submitType);
            if (null == forecastOrderParams.getSuccess()) {
                result.put("success", false);
                result.put("message", "预报单创建提交异常");
                return result;
            }

            return forecastOrderParams;
        } else {
            result.put("success", false);
            result.put("message", "提交参数空白");
            return result;
        }


    }

    private CreateForecastOrderParamsResponse planOrderSubmit(JSONObject submitFields, String submitType) {
        //create forecast order response object
        CreateForecastOrderParamsResponse result = new CreateForecastOrderParamsResponse();
        //create forecast order input params
        ForecastOrderSDO forecastOrderInputRequest = new ForecastOrderSDO();


        //according to address ,copy some channel value to create params
        String addressCode = submitFields.getString("addressCode");
        String addressId = submitFields.getString("addressId");
        if (StringUtils.isNotBlank(addressCode)) {
//            PageQueryAddressListResponse listResult = otsPlatformEnhanceService.pageQueryAddressList(new PageQueryAddressListRequest() {{
//                setAddressCode(addressCode);
//            }});
            PageQueryAddressListByPrincipalResponse listResult = otsPlatformEnhanceService.pageQueryAddressListByPrincipal(new PageQueryAddressListByPrincipalRequest() {{
                setId(addressId);
            }});

            if (Objects.nonNull(listResult) && CollectionUtils.isNotEmpty(listResult.getResult())) {
                CustomerAddressSDO customerAddressSDO = JSONObject.parseObject(JSONObject.toJSONString(listResult.getResult().get(0)),CustomerAddressSDO.class);
                BeanUtils.copyProperties(customerAddressSDO, forecastOrderInputRequest, "id");
                forecastOrderInputRequest.setSaleChannelCode(customerAddressSDO.getOrgSaleChannelCode());
                forecastOrderInputRequest.setSaleChannelName(customerAddressSDO.getOrgSalesChannelName());
                forecastOrderInputRequest.setOrganizationCode(customerAddressSDO.getOrgSaleOrganizationCode());
                forecastOrderInputRequest.setOrganizationName(customerAddressSDO.getOrgSalesOrganizationName());
                forecastOrderInputRequest.setDepartmentCode(customerAddressSDO.getOrgSaleDepartmentCode());
                forecastOrderInputRequest.setDepartmentName(customerAddressSDO.getOrgSalesDepartmentName());
                forecastOrderInputRequest.setCustomerCode(customerAddressSDO.getCustomerCode());
                forecastOrderInputRequest.setCustomerName(customerAddressSDO.getCustomerName());
                forecastOrderInputRequest.setChannelCode(customerAddressSDO.getChannelCode());
                forecastOrderInputRequest.setChannelName(customerAddressSDO.getChannelName());
                forecastOrderInputRequest.setSalesmanCode(customerAddressSDO.getPrincipal());
                forecastOrderInputRequest.setSalesmanName(customerAddressSDO.getPrincipalName());
                forecastOrderInputRequest.setBisUnitCode(customerAddressSDO.getOrgBussinessUnitCode());
                forecastOrderInputRequest.setCustomerPrincipalName(customerAddressSDO.getCustomerPrincipalName());
                forecastOrderInputRequest.setCustomerPrincipalId(customerAddressSDO.getCustomerPrincipal());

            }
        }

        //add some create params of page submit
        forecastOrderInputRequest.setStatus(ForecastStatusEnum.DRAFT.getNumValue());
        forecastOrderInputRequest.setOrderType(submitFields.getString("orderTypeCode"));
        forecastOrderInputRequest.setReceiveAddressCode(addressCode);
        forecastOrderInputRequest.setCustomerReferenceNo(submitFields.getString("customerReferenceNo"));
        forecastOrderInputRequest.setRemark(submitFields.getString("remark"));
        forecastOrderInputRequest.setTransportModeCode(submitFields.getString("transportModeCode"));
        forecastOrderInputRequest.setCustomerExpectTDate(getDateTime(Long.valueOf(submitFields.getString("customerExpectTDate"))));
        forecastOrderInputRequest.setCreditBalance(submitFields.getString("creditBalance"));
        forecastOrderInputRequest.setFeeBalance(submitFields.getString("feeBalance"));
        forecastOrderInputRequest.setWareHouseCode(submitFields.getString("wareHouseCode"));
        forecastOrderInputRequest.setWareHouseName(submitFields.getString("wareHouseName"));

        //添加发货仓name
        if (StringUtils.isNotBlank(submitFields.getString("wareHouseCode"))) {
            QueryCargoZoneByIdResponse warehouseInfoResult = unifiedInventoryService.queryCargoZoneById(new QueryCargoZoneByIdRequest() {{
                setCargoZoneIdList(Arrays.asList(forecastOrderInputRequest.getWareHouseCode()));
            }});
            if (Objects.nonNull(warehouseInfoResult) &&  CollectionUtils.isNotEmpty(warehouseInfoResult.getResult())) {
                JSONObject jsonObject = (JSONObject) JSONObject.toJSON(warehouseInfoResult.getResult().get(0));
                forecastOrderInputRequest.setWareHouseName(jsonObject.getString("name"));
            }
        }


        log.info("forecastOrderInputRequest:" + JSONObject.toJSONString(forecastOrderInputRequest));
        CreateForecastOrderParamsRequest createForecastOrderParamsRequest = new CreateForecastOrderParamsRequest();

        createForecastOrderParamsRequest.setForecastOrderSDOList(new ArrayList<ForecastOrderSDO>() {{
            add(forecastOrderInputRequest);
        }});

        createForecastOrderParamsRequest.setHasSubOrders(false);
        CreateForecastOrderParamsResponse forecastOrderParams = null;
        try {
            forecastOrderParams = otsForecastSalesService.createForecastOrderParams(createForecastOrderParamsRequest);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("小程序创建预报订单错误:",e);

            result.setMessage(e.getMessage());
            result.setSuccess(false);
            return result;
        }

        if (Objects.isNull(forecastOrderParams)||!forecastOrderParams.getSuccess() || Objects.isNull(forecastOrderParams.getResult())) {
            result.setMessage(forecastOrderParams.getMessage());
            result.setSuccess(false);
            return result;

        }

        LinkedTreeMap firstCreate = (LinkedTreeMap) forecastOrderParams.getResult();
        List<String> orderIds = (List<String>) firstCreate.get("orderIds");

        //货品明细的新增 通过主单ID去查询下属的所有子单，然后进行增删改的判断

        JSONArray goodDetailArray = submitFields.getJSONArray("goodDetail");
        if (Objects.nonNull(goodDetailArray) && CollectionUtils.isNotEmpty(goodDetailArray)) {

            List<ForecastOrderLineSDO> orderLineSDOList = goodDetailArray.toJavaList(ForecastOrderLineSDO.class);

            log.info("订单创建成功：" + orderIds.get(0));
            orderLineSDOList.stream().forEach(o -> {
                o.setMainOrderId(orderIds.get(0));
                o.setId(null);
            });
            forecastOrderInputRequest.setId(orderIds.get(0));
            if (MapUtils.isEmpty(forecastOrderInputRequest.getFeatures())){
                forecastOrderInputRequest.setFeatures(new HashMap<>());
            }
            forecastOrderInputRequest.getFeatures().put("validCheck","false");
            forecastOrderInputRequest.setForecastOrderLineSDOList(orderLineSDOList);
            createForecastOrderParamsRequest.setHasSubOrders(true);
            log.info("创建订单入参：" + JSONObject.toJSONString(createForecastOrderParamsRequest));
            try {
                forecastOrderParams = otsForecastSalesService.createForecastOrderParams(createForecastOrderParamsRequest);
            } catch (Exception e) {
                log.error("打印下异常", e);
                result.setMessage(e.getMessage());
                result.setSuccess(false);
                return result;
            }

            if (Objects.isNull(forecastOrderParams)|| !forecastOrderParams.getSuccess()){
                return forecastOrderParams;

            }
        }

        if ("submit".equalsIgnoreCase(submitType)) {
            EmployeeGetCurrentLoginResponse currentLoginResponse = bcOtsService.employeeGetCurrentLogin();

            SubmitForecastRequest submitForecastRequest = new SubmitForecastRequest();

            List<ForecastOrderSDO> forecastOrderSDOList = createForecastOrderParamsRequest.getForecastOrderSDOList();


            ApiContext apiContext = new ApiContext();
            if (Objects.nonNull(currentLoginResponse)) {
                BeanUtils.copyProperties(currentLoginResponse, apiContext);
            }
            submitForecastRequest.setForecastOrderSDOList(forecastOrderSDOList);
            submitForecastRequest.setApiContext(apiContext);
            Result<Boolean> booleanResult = null;
            try {
                booleanResult = forecastOrderWriteService.submitForecast(submitForecastRequest);

            } catch (Exception e) {
                log.error("打印异常", e);
                result.setMessage(e.getMessage());
                result.setSuccess(false);
                return result;

            }
            Result<Boolean> finalBooleanResult = booleanResult;
            return new CreateForecastOrderParamsResponse() {{
                setMessage(finalBooleanResult.getMessage());
                setResult(finalBooleanResult.getResult());
                setSuccess(finalBooleanResult.isSuccess());
            }};

        }

        log.info("预报订单创建返回结果" + JSONObject.toJSONString(forecastOrderParams));
        return forecastOrderParams;

    }


    private Date getDateTime(Long charDateTime) {

        return new Date(charDateTime);
    }

    private ForecastOrderSDO castCustomerToForecastOrderSDO() {
        return null;
    }

    //构造常用货品类目
    public List<ScItemGoods> buildGoodsList(List<ScItemGoods> queryGoodsList, List goodsIdList) {
        if (CollectionUtils.isEmpty(goodsIdList)) {
            return queryGoodsList;
        }
        if (CollectionUtils.isEmpty(queryGoodsList)) {
            return queryGoodsList;
        }
        Set<String> goodsIdSet = new HashSet();
        for (Object goodsId : goodsIdList) {
            goodsIdSet.add(goodsId.toString());
        }
        List list = new ArrayList();
        for (String goodsId : goodsIdSet) {
            boolean flg = false;
            for (ScItemGoods scItemGoods : queryGoodsList) {
                flg = false;
                if (org.apache.commons.collections.CollectionUtils.isNotEmpty(scItemGoods.getGoodsList())) {
                    for (Object goodsObj : scItemGoods.getGoodsList()) {
                        JSONObject goodsJson = (JSONObject) JSONObject.toJSON(goodsObj);
                        if (goodsId.equals(goodsJson.getString("id"))) {
                            list.add(goodsObj);
                            flg = true;
                            break;
                        }
                    }
                }
                if (flg) break;
            }
        }
        if (CollectionUtils.isEmpty(list)) {
            return queryGoodsList;
        }
        ScItemGoods scItemGoods = new ScItemGoods();
        //端上构造的虚假常用货品类目,库中无该类目
        scItemGoods.setLabel("常用货品");
        scItemGoods.setGoodsList(list);

        List<ScItemGoods> scItemGoodsList = new ArrayList<>();
        scItemGoodsList.add(scItemGoods);
        scItemGoodsList.addAll(queryGoodsList);

        return scItemGoodsList;
    }


    private String getTopLevelCode(String id,Integer type){
        Result<List<OrganizationSDO>> topOrganizationList = organizationQueryService.getTopOrganizationList(new IdQueryRequest() {{
            setId(id);
            setType(type);
        }});

        if (Objects.nonNull(topOrganizationList)&&CollectionUtils.isNotEmpty(topOrganizationList.getResult())){
            List<OrganizationSDO> collect = topOrganizationList.getResult().stream().filter(o -> o.getType() == 103).collect(Collectors.toList());

            if (CollectionUtils.isNotEmpty(collect)){
                return Optional.ofNullable(collect.get(0).getId()).orElse("");
            }

        }
        return "";
    }
    @Data
    public class CreateSelectList {
        private List<Info> orderType;
        private List<Info> customerAddress;
        private List<Info> deliveryType;
        private List<Info> deliveryWarehouse;
        private List<ScItemGoods> scItemGoodsList;
        private List goodsIdList;
        private Boolean disableRefNo;
    }


    @Data
    public static class Info {
        private String label;
        private String value;
    }
}
